// pages/order/statistics/sale/sale-statistics.js
import {
  dsx
} from '~/tools/datax'
import {
  users
} from '~/tools/users'
import {
  ui
} from '~/tools/ui'
import {
  shops
} from '~/tools/shops';
import {
  dateTool
} from '~/tools/date'
import {
  adv
} from '~/tools/adv';
Page({
  data: {
    dateRange: {
      start: 0,
      end: 0
    },
    defaultDateRanges: ['周', '月', '年'],
    curDateRangeIndex: 1,
    order: [],
    stts: {},
    advanced: false,
    selShops: {
      value: 'all',
      label: '所有门店',
      options: [{
        label: '所有门店',
        value: 'all'
      }],
    },
    selDelivery: {
      value: 'all',
      label: '所有配送员',
      options: [{
        label: '所有配送员',
        value: 'all'
      }],
    }
  },
  onLoad(options) {
    this.initDateRange();
    this.updateDateRange();
    this.loadShops();
    this.loadOrders();
    this.loadDelivery();
  },
  loadShops() {
    const {
      selShops
    } = this.data
    const shopList = shops.getShopList()
    for (const s of shopList) {
      selShops.options.push({
        label: s.name,
        value: s.id
      })
    }
    this.setData({
      selShops
    })
  },
  loadOrders() {
    ui.loading()

    const {
      start,
      end
    } = this.data.dateRange
    const shop = this.data.selShops.value,
      deli = this.data.selDelivery.value
    wx.cloud.callFunction({
      name: 'deliveryStatistics',
      data: {
        start,
        end,
        shop,
        deli
      }
    }).then(res => {
      ui.loading(false)
      // console.log(res.result.stts)
      this.setData({
        stts: res.result.stts
      })
    }).catch(err => {
      ui.loading(false)
      console.error(err)
    })
  },
  loadDelivery() {
    ui.loading()
    const _ = dsx.cmd
    const shopid = this.data.selShops.value;
    const selDelivery = this.data.selDelivery,
      options = selDelivery.options;
    options.splice(1, options.length - 1)
    dsx.getAll('users', {
      role: _.in(['master', 'delivery']),
      'shop.id': shopid == 'all' ? _.exists(true) : _.eq(shopid)
    }, {
      _openid: 1,
      shop: 1,
      personInfo: 1
    }).then(deli => {
      for (const d of deli) {
        options.push({
          value: d._openid,
          label: d.personInfo.nickName
        })
      }
      this.setData({
        selDelivery
      })
      ui.loading(false)
    })
  },
  initDateRange() {
    const dateRange = this.data.dateRange;
    dateRange.start = this.getStartTime();
    dateRange.end = new Date().getTime()
    this.setData(dateRange)
  },
  updateDateRange() {
    const dpStart = this.selectComponent("#dpstart"),
      dpEnd = this.selectComponent("#dpend");
    dpStart.initTimestamp(this.data.dateRange.start);
    dpEnd.initTimestamp(this.data.dateRange.end)
  },
  getStartTime() {
    const {
      defaultDateRanges,
      curDateRangeIndex
    } = this.data;
    const now = new Date()
    let d = null;
    switch (defaultDateRanges[curDateRangeIndex]) {
      case '周':
        let day = now.getDay();
        if (day == 0) day += 1;
        d = new Date(now.getTime() - (day - 1) * 3600 * 24 * 1000);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
      case '月':
        d = new Date(now.getTime() - (now.getDate() - 1) * 3600 * 24 * 1000);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
      case '年':
        return new Date(now.getFullYear(), 0).getTime();
    }
    return now.getTime();
  },
  async doStatistics() {
    this.loadOrders()
  },
  onChangeSelShop(e) {
    const value = e.detail.value
    let label = ''
    for (const o of this.data.selShops.options) {
      if (o.value == value) {
        label = o.label;
        break;
      }
    }
    this.setData({
      'selShops.value': value,
      'selShops.label': label
    });
    this.loadDelivery()
  },
  onChangeSelDeli(e) {
    const value = e.detail.value
    let label = ''
    for (const o of this.data.selDelivery.options) {
      if (o.value == value) {
        label = o.label;
        break;
      }
    }
    this.setData({
      'selDelivery.value': value,
      'selDelivery.label': label
    });
  },
  onAdvancedTap() {
    const {
      advanced
    } = this.data
    this.setData({
      advanced: !advanced
    })
  },
  dateRangeTap(e) {
    let selIndex = ui.eventData(e, 'selindex')
    this.setData({
      curDateRangeIndex: selIndex
    })
    this.initDateRange()
    this.updateDateRange()
  },
  onPickStartDate(e) {
    const {
      timestamp
    } = e.detail;
    // console.log(new Date(timestamp))
    this.setData({
      dateRange: {
        start: timestamp,
        end: this.data.dateRange.end
      }
    })
    this.justifyDateRange()
  },
  onPickEndDate(e) {
    const {
      timestamp
    } = e.detail;
    this.setData({
      dateRange: {
        start: this.data.dateRange.start,
        end: dateTool.dayEnd(timestamp)
      }
    })
    this.justifyDateRange()
  },
  justifyDateRange() {
    let {
      start,
      end
    } = this.data.dateRange

    this.setData({
      curDateRangeIndex: -1
    })
    if (start > end) {
      end = dateTool.dayEnd(start);
      this.setData({
        dateRange: {
          start,
          end
        }
      })
      this.updateDateRange();
    }

  },
  onReady() {

  },
  onShow() {

  },
  onHide() {

  },
  onUnload() {

  },
  onPullDownRefresh() {

  },
  onReachBottom() {

  },
  onShareAppMessage() {

  }
})